package com.xx.cloud.pay.config.whitelist;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xx.cloud.pay.entity.DataClient;
import com.xx.cloud.pay.mapper.DataClientMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;

@Component
public class IPWhitelistInterceptor implements HandlerInterceptor {

    @Autowired
    private DataClientMapper repository;

    @Override
    public boolean preHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {

        if (handler instanceof HandlerMethod handlerMethod) {

            //原始handler
            //HandlerMethod handlerMethod = (HandlerMethod) handler;

            IPWhitelist ipWhitelist = handlerMethod.getMethodAnnotation(IPWhitelist.class);
            if (ipWhitelist != null) {
                String ip = request.getRemoteAddr();

                List<String> collect = repository.selectList(new LambdaQueryWrapper<DataClient>().eq(DataClient::getClientIp, ip))
                        .stream().map(DataClient::getClientIp).toList();

                if (!collect.contains(ip)) {
                    response.setContentType("application/json;charset=UTF-8");
                    response.setCharacterEncoding("UTF-8");

                    response.getWriter().write(
                            """
                                    {
                                        "msg": "请开通权限！",
                                        "code": "403"
                                    }
                                    """
                    );

                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    return false;
                }
            }
        }
        return true;
    }

}